<?php
namespace Admin\Controller;
use Think\Controller;
/**
 * 林群伟后台首页
 */
use Common\Service\ApiService;  //接口服务调用api
class PublicController extends Controller {
  
   /**
     * 用户名
     * @param type $username 用户名
     * @param type $password  密码
     * @param type $verify  验证码
     */
    public function login($username = null, $password = null, $verify = null) {

    

        if (IS_POST) {
    
            //判断验证码
            if (!verify_check($verify)) {
               // $this->error(L("ERROR_VERIFY_FORM"));
            } 
            header("Content-type:text/html;charset=utf-8");
            $client = new ApiService;
            $clientapi = $client->useService("User");

            try {
             
                //RPC远程登陆
                $uid = $clientapi->login($username, $password);

            } catch (Exception $e) {
                $error = $e->getMessage();
            }

            if (0 < $uid) {    
                //登录成功
                $user = D("Members");
                $userinfo = $user->login($uid);
               
                if ($userinfo) {
                    $this->success("登陆成功", U('Index/index'));
                } else {
                    $this->error($user->getError());
                }
            } else { //登录失败
          
                switch ($uid) {
                    case -1: $error = '用户不存在或被禁用！';
                        break; //系统级别禁用
                    case -2: $error = '密码错误！';
                        break;
                    default:
                        $ar = explode(":", $uid);
                        if (is_array($ar)) {
                            $error = $ar[1];
                        } else {
                            $error = '未知错误！';
                        }
                        break; // 0-接口参数错误（调试阶段使用）
                }
            }
            $this->error($error);
        }
        $this->display();
    }

   public function logout() {
        if (is_login()) {
            D('Members')->logout();
            $this->success('退出成功！', U('login'), false);
        } else {
            $this->redirect('login');
        }
    }
    public function reg(){
        if(IS_POST){
            //$wakuang_type = I("wakuang_type");
            //$wjs = D("WakuangjiSet")->where(array("id" => $wakuang_type))->find();
            
      
            //判断自已是否足够法诺币进行新建
            M()->startTrans();

            if (D("UcenterMembers")->create()) {
                $newdata = array(
                    //"uid"=>$addid,
                    "nickname" => I("nickname"),
                    "wakuang_type" => I("wakuang_type"),
                    "blank_no" => I("blank_no"),
                    "blank_name" => I("blank_name"),
                );

                if (D("Members")->create($newdata)) {
                    if ($addid = D("UcenterMembers")->add()) {

                        $wakuang_name = $wjs["name"];
                        $newdata = array(
                            "uid" => $addid,
                            "nickname" => I("nickname"),
                            "wakuang_type" =>0, //$wakuang_type,
                            "wakuang_name" => "普通交易用户",//$wakuang_name,
                            "blank_no" => I("blank_no"),
                            "blank_name" => I("blank_name"),
                            "status" => 0,
                        );
                        if (D("Members")->create($newdata)) {
                            if (D("Members")->regadd($newdata)) {
                              

                                M()->commit();
                                $this->success("操作成功,等待审核", U('login'));
                            } else {
                                M()->rollback();
                                D("UcenterMembers")->where(array("id" => $addid))->delete();
                                D("Member")->where(array("id" => $addid))->delete();
                                $this->error("操作失败");
                            }
                        }
                    }
                } else {
                    M()->rollback();
                    $this->error(D("Members")->getError());
                }
            } else {
                M()->rollback();
                $this->error(D("UcenterMembers")->getError());
            }
        }
          //获取挖矿类型
        $wakuang_type = D("WakuangjiSet")->where(array("status" => 1))->select();
        $this->assign("wakuang_type", $wakuang_type);
        $this->display();
    }


    /**
     * 验证码
     */
    public function verify() {
        $verify = new \Think\Verify();
        $verify->entry(1);
    }

    /**
     * 供应商注册
     */
    public function regedit() {
        if (IS_POST) {

            $upload = new \Think\Upload(); // 实例化上传类
            $upload->maxSize = 3145728; // 设置附件上传大小
            $upload->exts = array('jpg', 'gif', 'bmp', 'png'); // 设置附件上传类型
            $upload->rootPath = './Public/Uploads/yiye/'; // 设置附件上传根目录
            $upload->savePath = ''; // 设置附件上传（子）目录
            // 上传文件 
            $info = $upload->upload();
            if (!$info) {// 上传错误提示错误信息
                $this->error($upload->getError());
            } else {// 上传成功

     
                $email=time().rand(100,9999).'@ad.com';
                $User = new UserApi;
                $uid = $User->register($_POST["username"], $_POST["password"], $email);
       
                if (0 < $uid) { //注册成功
                $regdata["uid"]=$uid;
                $regdata["nickname"] = $_POST["username"];
                $regdata["yiyue"] = $info['yiyue']['savepath'] . $info['yiyue']['savename'];
                $regdata["quke"] = $info['quke']['savepath'] . $info['quke']['savename'];
                $regdata["fuben"] = $info['fuben']['savepath'] . $info['fuben']['savename'];
                    if (!M('Members')->add($regdata)) {
                        //添加到用户组中
                        $this->error('用户添加失败！');
                    } else {
                        M("AuthGroupAccess")->add(array("uid" => $uid, "group_id" => 5));
                        $this->success('用户添加成功，等待审核！', U('login'));
                    }
                } else { //注册失败，显示错误信息
                    $this->error($this->showRegError($uid));
                }
            }
        }
        $this->display();
    }
 /**
     * 获取用户注册错误信息
     * @param  integer $code 错误编码
     * @return string        错误信息
     */
    private function showRegError($code = 0) {
        switch ($code) {
            case -1: $error = '用户名长度必须在16个字符以内！';
                break;
            case -2: $error = '用户名被禁止注册！';
                break;
            case -3: $error = '用户名被占用！';
                break;
            case -4: $error = '密码长度必须在6-30个字符之间！';
                break;
            case -5: $error = '邮箱格式不正确！';
                break;
            case -6: $error = '邮箱长度必须在1-32个字符之间！';
                break;
            case -7: $error = '邮箱被禁止注册！';
                break;
            case -8: $error = '邮箱被占用！';
                break;
            case -9: $error = '手机格式不正确！';
                break;
            case -10: $error = '手机被禁止注册！';
                break;
            case -11: $error = '手机号被占用！';
                break;
            default: $error = '未知错误';
        }
        return $error;
    }
    /**
     * 支付结果返回
     */
    public function notify() {
        $apitype = I('get.apitype');
        $pay = new \Think\Pay($apitype, C('payment.' . $apitype));
        if (IS_POST && !empty($_POST)) {
            $notify = $_POST;
        } elseif (IS_GET && !empty($_GET)) {
            $notify = $_GET;
            unset($notify['method']);
            unset($notify['apitype']);
        } else {
            exit('Access Denied');
        }
        //验证
        if ($pay->verifyNotify($notify)) {
            //获取订单信息
            $info = $pay->getInfo();

            if ($info['status']) {
                $payinfo = M("Pay")->field(true)->where(array('out_trade_no' => $info['out_trade_no']))->find();
                if ($payinfo['status'] == 0 && $payinfo['callback']) {
                    session("pay_verify", true);
                    $check = R($payinfo['callback'], array('money' => $info['money'], 'param' => unserialize($payinfo['param'])));
                    if ($check !== false) {
                        $uid = $_SESSION["user_auth"]["uid"];
                        M("Pay")->where(array('out_trade_no' => $info['out_trade_no']))->setField(array('update_time' => time(), 'status' => 1, 'uid' => $uid));
                    }
                }
                if (I('get.method') == "return") {
                    redirect($payinfo['url']);
                } else {
                    $pay->notifySuccess();
                }
            } else {
                $this->error("支付失败！");
            }
        } else {
            E("Access Denied");
        }
    }
}